<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-title">欢迎登录</div>
      <div class="login-subtitle">团队小助理</div>

      <el-form :model="data.form" ref="formRef" :rules="data.rules" class="login-form">
        <el-form-item prop="phone">
          <el-input :prefix-icon="User" size="large" v-model="data.form.phone" placeholder="请输入手机号"
            class="custom-input" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" size="large" v-model="data.form.password" placeholder="请输入密码" show-password
            class="custom-input" />
        </el-form-item>
        <el-form-item>
          <el-button size="large" type="primary" class="login-button" @click="login">登 录</el-button>
        </el-form-item>
      </el-form>

      <div class="register-link">
        还没有账号？请 <router-link to="/register" class="link-text">注册</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import request from "@/utils/request";
import { ElMessage } from "element-plus";
import router from "@/router";
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();

const data = reactive({
  form: {},
  rules: {
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度6-20位', trigger: 'blur' }
    ]
  }
})

const formRef = ref()

const login = async () => {
  const isValid = await formRef.value.validate().catch(() => false);
  if (!isValid) return;

  try {
    // 显示加载状态
    const loading = ElMessage({
      message: '登录中...',
      type: 'info',
      duration: 0,
      showClose: false
    });

    const res = await request.post('/api/auth/login', data.form);
    loading.close();

    if (res && res.code === '200') {
      ElMessage.success('登录成功');

      const userData = {
        id: res.data?.id,
        name: res.data?.username,
        username: res.data?.username,
        phone: data.form.phone
      };

      // 存储到localStorage
      localStorage.setItem('system-user', JSON.stringify(userData));

      // 存储到Pinia store
      userStore.setUser({
        username: res.data?.username,
        email: res.data?.email || '',
        id: res.data?.id
      });

      console.log('用户登录成功:', userData);
      router.push('/home');
    } else {
      ElMessage.error(res.msg || '登录失败');
    }
  } catch (error) {
    // 记录错误信息到控制台（非错误级别）
    console.info({
      message: '登录错误',
      error: error.message,
      timestamp: new Date().toISOString(),
      type: 'login_error'
    });

    // 处理不同类型的错误
    if (error.response) {
      // 服务器响应错误
      const status = error.response.status;
      const data = error.response.data;
      
      switch (status) {
        case 400:
          ElMessage.error(data.msg || '请求参数错误，请检查输入信息');
          break;
        case 401:
          ElMessage.error(data.msg || '账号或密码错误');
          break;
        case 403:
          ElMessage.error('账号被禁用，请联系管理员');
          break;
        case 422:
          ElMessage.error(data.msg || '数据验证失败');
          break;
        case 500:
          ElMessage.error('服务器内部错误，请稍后重试');
          break;
        case 503:
          ElMessage.error('服务暂时不可用，请稍后重试');
          break;
        default:
          ElMessage.error(data.msg || `登录失败 (错误代码: ${status})`);
      }
    } else if (error.request) {
      // 网络错误
      if (error.code === 'ECONNABORTED') {
        ElMessage.error('请求超时，请检查网络连接后重试');
      } else if (error.message.includes('Network Error')) {
        ElMessage.error('网络连接失败，请检查网络设置');
      } else {
        ElMessage.error('网络请求失败，请稍后重试');
      }
    } else {
      // 其他错误
      ElMessage.error('手机号或密码错误');
    }
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #7f7fd5, #86a8e7, #91eae4);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

.login-box {
  width: 380px;
  padding: 40px 35px;
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  transform: translateY(0);
}

.login-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
}

.login-title {
  font-weight: bold;
  font-size: 28px;
  text-align: center;
  margin-bottom: 8px;
  color: #1450aa;
  letter-spacing: 2px;
}

.login-subtitle {
  font-size: 16px;
  text-align: center;
  margin-bottom: 30px;
  color: #666;
  letter-spacing: 1px;
}

.login-form {
  margin-bottom: 20px;
}

.custom-input :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) inset;
  border-radius: 8px;
  padding: 0 15px;
  transition: all 0.3s;
}

.custom-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #1967e3 inset;
}

.custom-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #1967e3 inset;
}

.login-button {
  width: 100%;
  border-radius: 8px;
  background: linear-gradient(90deg, #1450aa, #1967e3);
  border: none;
  font-weight: 500;
  letter-spacing: 2px;
  transition: all 0.3s;
  height: 44px;
}

.login-button:hover {
  background: linear-gradient(90deg, #1967e3, #1450aa);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(25, 103, 227, 0.3);
}

.register-link {
  text-align: right;
  font-size: 14px;
  color: #666;
  margin-top: 15px;
}

.link-text {
  color: #1967e3;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s;
}

.link-text:hover {
  color: #1450aa;
  text-decoration: underline;
}
</style>
